<template>
  <div v-loading="loading" style=" box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);height:500px;overflow: auto;">
     <el-table
    ref="multipleTable"
    :data="dataList"
    tooltip-effect="dark"
    style="width: 100%;"
    v-loading="dataListLoading"
    @selection-change="handleSelectionChange">
    <el-table-column
      type="selection"
      width="55">
    </el-table-column>
    <el-table-column
      :show-overflow-tooltip="true"
      prop="regionName"
      label="所属区域"
       width="240"
      >
    </el-table-column>
    <el-table-column
      :show-overflow-tooltip="true"
      prop="name"
      label="设备名称"
      width="100"
      >
    </el-table-column>
    <el-table-column
      :show-overflow-tooltip="true"
      prop="installationAddress"
      label="安装地址"
       width="100"
      >
    </el-table-column>
    <el-table-column
      label="具体权限"
       width="200"
      >
       <template slot-scope="scope">
         <!-- <el-button  type="text"  size="small" @click="devicePermissionTypeHandle(scope.row)" >具体权限</el-button> -->
         <el-popover
          placement="right"
          width="400"
          trigger="click">
          <el-select
          v-model="value"
          multiple
          filterable
          allow-create
          default-first-option
          placeholder="请选择设备具体权限">
            <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value">
            </el-option>
          </el-select>
              <el-button  type="primary"  size="small" :loading="btnLoading" @click="devicePermissionTypeSybmit(scope.row)" >{{ $t('handle.confirm') }}</el-button>
          <el-button slot="reference" @click ="giveValue(scope.row)">具体权限</el-button>
          <!-- <el-badge slot="reference" :value="scope.row.permissionType.length" class="item" type="primary">
             <el-button @click ="giveValue(scope.row)" type="small">具体权限</el-button>
          </el-badge> -->
        </el-popover>
       </template>
    </el-table-column>
  </el-table>
  <div style="margin-top: 20px;text-align:center">
    <el-button v-if="dataShow" type="primary"  @click="submit()">{{ $t('handle.confirm') }}</el-button>
    <el-button @click="toggleSelection()">取消选择</el-button>
  </div>
  </div>
</template>
<script>
import { setTimeout } from "timers";
export default {
  data() {
    return {
      typeCount: "",
      btnLoading: false,
      options: [
        {
          value: "1",
          label: "APP"
        }
      ],
      value: [],

      visible: false,
      dataListLoading: false,
      loading: false,
      communityId: "",
      dataShow: false,
      superAdmin: sessionStorage.getItem("superAdmin"),
      personnelId: "",
      regionId: "",
      dataList: [],
      multipleSelection: []
    };
  },
  computed: {},
  // 引入的组件
  components: {},
  created() {
    this.initTypeDict();
  },
  activated() {},
  methods: {
    initTypeDict() {
      this.$http({
        url: "dg-ic/ic/dict/type/device_permission_type",
        method: "get"
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.options = data.data;
        }
      });
    },
    giveValue(row) {
      // 发送请求给后台
      this.$http({
        url: `/dg-ic/ic/device/permission/type/info`,
        method: "get",
        params: this.$http.adornParams({
          deviceId: row.id,
          personnelId:this.personnelId
        })
      }).then(({ data }) => {
        if (data && data.code === 0) {
          if (data.data[0] === "") {
            this.value = [];
          } else {
            this.value = data.data;
          }
        } else {
          this.$message.error(data.msg);
        }
      });
    },
    devicePermissionTypeSybmit(row) {
      this.btnLoading = true;
      this.$http({
        url: `/dg-ic/ic/device/permission/type/update`,
        method: "post",
        data: this.$http.adornData({
          deviceId: row.id,
          personnelId:this.personnelId,
          permissionType: this.value
        })
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.btnLoading = false;
          this.$message({
            message: "操作成功",
            type: "success",
            duration: 1500,
            onClose: () => {}
          });
        } else {
          this.btnLoading = false;
          this.$message.error(data.msg);
        }
      });
    },
    init(regionId, populationCoding, communityId) {
      this.communityId = communityId;
      this.regionId = regionId;
      this.personnelId = populationCoding;
      if (this.dataList) {
        this.dataListLoading = true;
        // 获取后端数据
        this.$http({
          url: `/dg-ic/ic/device/permission/list`,
          method: "get",
          params: this.$http.adornParams({
            // regionId: regionId,
            flag: 1,
            personnelId: populationCoding,
            housingEstateId:
              sessionStorage.getItem("thiscommunityId") === "null"
                ? null
                : sessionStorage.getItem("thiscommunityId")
          })
        }).then(
          ({ data }) => {
            if (data && data.code === 0) {
              this.dataList = data.data;
              if (this.dataList.length > 0) {
                this.dataShow = true;
              } else {
                this.dataShow = false;
              }
              this.dataList.forEach(row => {
                if (row.isSelected == true) {
                  setTimeout(() => {
                    this.$refs.multipleTable.toggleRowSelection(row);
                  }, 100);
                }
              });
              this.dataListLoading = false;
            } else {
              this.$message.error(data.msg);
              this.dataListLoading = false;
            }
          },
          error => {
            if (error.response.status === 403) {
              this.$message.error("你没有权限");
              this.dataListLoading = false;
            } else {
              this.$message.error("系统错误，请联系管理员");
              this.dataListLoading = false;
            }
          }
        );
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    submit() {
      this.loading = true;
      // 提交选中后的数据
      var ids = this.multipleSelection.map(item => {
        return item.id;
      });
      var regionIds = this.multipleSelection.map(item => {
        return item.regionId;
      });
      var housingEstateIds = this.multipleSelection.map(item => {
        return item.housingEstateId;
      });
      this.$http({
        url: `/dg-ic/ic/device/permission/update`,
        method: "post",
        data: this.$http.adornData({
          // regionId: this.regionId,
          regionIds: regionIds,
          personnelId: this.personnelId,
          // housingEstateId:sessionStorage.getItem("thiscommunityId")==="null"? this.communityId:sessionStorage.getItem("thiscommunityId"),
          housingEstateIds: housingEstateIds,
          deviceIds: ids
        })
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.$message({
            message: "操作成功",
            type: "success",
            duration: 1500,
            onClose: () => {
              this.loading = false;
              this.$emit("refresh", true);
              // this.$emit("close", false);
            }
          });
          // 推送消息给设备
          // var ips = this.dataList.map(item => {
          //   return item.ip;
          // });
          // this.$http({
          //   url: `/dg-ic/ic/device/permission/sendMessage`,
          //   method: "post",
          //   data: this.$http.adornData({
          //     ips: ips
          //   })
          // }).then(({ data }) => {
          //   console.log(data)
          // });
        } else {
          this.$message.error(data.msg);
        }
      });
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    }
  }
};
</script>
<style>
.el-badge__content is-fixed {
  top: 9px;
}
</style>




